package org.chinasoft.service.impl;

import org.chinasoft.dao.RoleMapper;
import org.chinasoft.dao.RoleMenuMapper;
import org.chinasoft.dao.UserRoleMapper;
import org.chinasoft.entity.Menu;
import org.chinasoft.entity.Role;
import org.chinasoft.entity.User;
import org.chinasoft.enums.SystemStatus;
import org.chinasoft.service.RoleService;
import org.chinasoft.utils.CheckUtil;
import org.chinasoft.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RoleMenuMapper roleMenuMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public Role getByRoleId(Long roleId) {
        return roleMapper.getByRoleId(roleId);
    }

    @Override
    public Set<Role> getAll() {
        return roleMapper.getAll()
                .stream()
                .filter(role -> SystemStatus.normal.getCode().equals(role.getStatus()))
                .collect(Collectors.toSet());
    }

    @Override
    @Transactional
    public Role save(Role role) {
        CheckUtil.check(StringUtil.isNotEmpty(role.getName()), "角色名不能为空");
        role.setStatus(SystemStatus.normal.getCode());
        roleMapper.save(role);
        return role;
    }

    @Override
    @Transactional
    public Role assignAccess(Role currentRole, List<Menu> menuList) {
        CheckUtil.check(currentRole.getRoleId() != null, "被赋角色不能为空");
        CheckUtil.check(!SystemStatus.removed.getCode().equals(currentRole.getStatus()), "该角色已经删除");

        // 获取被赋角色编号
        Long roleId = currentRole.getRoleId();

        // 去重
        roleMenuMapper.removeByRoleId(roleId);

        // 遍历权限集合,添加到角色-权限关系表中
        for (Menu menu : menuList) {
            Long menuId = menu.getMenuId();
            roleMenuMapper.save(roleId, menuId);
        }
        return currentRole;
    }

    @Override
    @Transactional
    public void removeByRoleId(Long roleId) {
        // 查询所要删除的角色编号
        Role role = roleMapper.getByRoleId(roleId);

        // 查询当前是否还有用户使用该角色
        Set<User> userSet = userRoleMapper.getUserSetByRoleId(roleId);
        CheckUtil.check(userSet == null || userSet.size() == 0, "该角色有用户在使用");

        // 修改角色编号为已删除
        role.setStatus(SystemStatus.removed.getCode());
        // 更新角色
        roleMapper.update(role);
    }

    @Override
    public void update(Role role) {
        CheckUtil.check(role != null && role.getRoleId() != null, "角色不能为空");
        CheckUtil.check(StringUtil.isNotEmpty(role.getName()), "角色名不能为空");
        CheckUtil.check(role.getStatus() != null, "角色状态不能为空");
        roleMapper.update(role);
    }
}
